<template>
  <div class="app-container">
    <div class="filter-container">
      <k-input
        v-model="listQuery.name"
        class="filter-item"
        is-search
        placeholder="饰品名称或关键词"
        :search-fun="handleFilter"
        @keyup.enter.native="handleFilter"
      />
    </div>

    <div class="top-right-btn-container">
      <k-button class="top-btn" value="自定义阶段分区" @click.native="customDivideZone" />
      <k-button class="top-btn" value="分阶段设置" @click.native="stageSetUp" />

      <div class="boxpricediv">
        <span style="white-space:nowrap;margin-right:10px">抽奖积分：</span>
        <el-input v-model.trim="price" disabled onkeyup="value=value.replace(/[^0-9.]/g,'')" style="width:140px;" />
        <span style="white-space:nowrap;margin-right:10px;margin-left:30px">抽奖折扣：</span>
        <el-input v-model.trim="rebate" disabled onkeyup="value=value.replace(/[^0-9.]/g,'')" style="width:140px;" />
        <span>%</span>
        <span style="white-space:nowrap;margin-right:10px;margin-left:20px">对应箱价：</span>
        <el-input v-model="boxPriceComputed" disabled style="width:140px;" />
        <k-button v-if="authorityHandle(51)" class="top-right-btn" value="完成配置" @click.native="finishSetting" />
      </div>
    </div>
    <div v-show="hasNoData" class="hasnodata_item">
      没有找到匹配数据
    </div>
    <div v-for="(tableItem,index) in tableDataList" :key="index" style="margin-bottom:50px">
      <!-- 数据开始 -->
      <k-button v-if="authorityHandle(51)" class="top-btn" value="添加礼品" @click.native="addBabyDialog(index)" />
      <k-button v-if="authorityHandle(51)" class="top-btn" value="删除礼品" @click.native="deletebaby(index)" />
      <el-divider>
        <p class="stage_flag">阶段 {{ index + 1 }}</p>
      </el-divider>
      <!--表格相关 -->
      <el-table
        :key="price + rebate"
        :data="tableItem"
        style="width: 100%"
        :height="tableItem.length > 0?800:200"
        fit
        highlight-current-row
        :span-method="arraySpanMethod"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" min-width="30" align="center" />
        <el-table-column type="index" label="序号" fixed width="50" align="center" />
        <el-table-column label="图标" fixed min-width="110" align="center">
          <template slot-scope="scope">
            <el-image style="width: 110px; height: 80px" :src="scope.row.iconUrl" :preview-src-list="[scope.row.iconUrl]" fit="fill" />
          </template>
        </el-table-column>
        <el-table-column prop="name" label="礼品名称" fixed min-width="100" show-overflow-tooltip align="center" />

        <el-table-column
          v-if="authorityHandle(51)"
          prop="customPrice"
          label="自定义价格"
          sortable
          min-width="100"
          align="center"
        >
          <editable-cell
            v-model="row.customPrice"
            slot-scope="{row}"
            :show-input="row.editMode"
            @keyup.enter.native="upcustomPrice(row)"
          >
            <span slot="content" :style="{'color':row.isUpdate === 2 ? '#3b425d':'#409EFF'}">{{ row.customPrice
            }}</span>
          </editable-cell>
        </el-table-column>

        <el-table-column v-else prop="customPrice" label="自定义价格" sortable min-width="100" align="center" />

        <!-- 概率 -->
        <el-table-column label="概率" min-width="150" align="center">
          <el-table-column align="center">
            <template slot="header">
              <div class="headeradd" @click="copyProbablityA(index)">
                <label>用户通道</label>
                <svg-icon icon-class="copy" />
              </div>
            </template>
            <!-- 期望价格 -->
            <el-table-column align="center">
              <template slot="header">
                <span>Z </span>
                <el-tooltip placement="top" content="期望价格">
                  <i class="el-icon-question" />
                </el-tooltip>
              </template>
              <el-table-column width="80" align="center">
                <template #header>
                  <span>{{ expectedPriceCal(0,index) }}</span>
                </template>
                <editable-cell
                  v-if="authorityHandle(51)"
                  v-model="row.userProbability"
                  slot-scope="{row}"
                  :show-input="row.editMode"
                  @inputChange="inputChange($event,0,index)"
                >
                  <span slot="content">{{ row.userProbability }}</span>
                </editable-cell>
                <span v-else>{{ row.userProbability }}</span>
              </el-table-column>
            </el-table-column>
            <el-table-column prop="name" align="center">
              <template slot="header">
                <span>∑ </span>
                <el-tooltip placement="top" content="概率和">
                  <i class="el-icon-question" />
                </el-tooltip>
              </template>
              <el-table-column width="80" align="center">
                <template #header>
                  <span>{{ probilitySumCal(0,index) }} </span>
                </template>
              </el-table-column>
            </el-table-column>
          </el-table-column>

          <el-table-column label="主播通道" align="center">
            <el-table-column align="center">
              <template slot="header">
                <span>Z </span>
                <el-tooltip placement="top" content="期望价格">
                  <i class="el-icon-question" />
                </el-tooltip>
              </template>
              <!-- 期望价格 -->
              <el-table-column width="80" align="center">
                <template #header>
                  <span>{{ fissionExpectedPriceCal(1,index) }} </span>
                </template>
                <editable-cell
                  v-if="authorityHandle(51)"
                  v-model="row.fissionProbability"
                  slot-scope="{row}"
                  :show-input="row.editMode"
                  @inputChange="inputChange($event,1,index)"
                >
                  <span slot="content">{{ row.fissionProbability }}</span>
                </editable-cell>
                <span v-else>{{ row.fissionProbability }}</span>
              </el-table-column>
            </el-table-column>
            <!-- 概率和 -->
            <el-table-column prop="name" align="center">
              <template #header>
                <span>∑ </span>
                <el-tooltip placement="top" content="概率和">
                  <i class="el-icon-question" />
                </el-tooltip>
              </template>
              <el-table-column width="80" align="center">
                <template slot="header">
                  <span>{{ fissionProbilitySumCal(1,index) }} </span>
                </template>
              </el-table-column>
            </el-table-column>
          </el-table-column>
        </el-table-column>
        <!-- end 概率 -->
        <el-table-column prop="categoryName" label="分类" min-width="50" show-overflow-tooltip align="center" />
        <el-table-column prop="goodsName" label="所在箱子/所属饰品" min-width="80" align="center" />
      </el-table>
    </div>
    <!-- 数据结束 -->
    <!-- 添加饰品 弹窗 -->
    <k-dialog
      :show-hide.sync="addBaby.showHide"
      :modal-append-to-body="false"
      :append-to-body="true"
      title="添加饰品"
      class="addBaby_dialog"
      :two-btn="true"
      :close-fun="handleCloseDialog"
      @click="saveGoodsList"
    >
      <el-select v-model="goodsValueModel" multiple style="width: 100%;" filterable placeholder="请选择">
        <el-option
          v-for="item in resultOpList"
          :key="item.lineId"
          :label="item.lineName"
          :value="item.lineId"
          @click.native="selectChange(item)"
        />
      </el-select>
      <div style="margin-top:10px;margin-bottom:200px">
        <el-tag
          v-for="(item ,index) of checkedGoodsList"
          :key="item.lineId"
          closable
          @close="handleBabyTagDelete(index)"
        >
          {{ item.lineName }}
        </el-tag>
      </div>
    </k-dialog>
    <!-- 智能阶段分区 弹窗 -->
    <k-dialog
      :show-hide.sync="customDivideZoneDialog"
      :modal-append-to-body="false"
      :append-to-body="true"
      title="自定义阶段分区"
      :show-foot="false"
      :two-btn="authorityHandle(51)"
      @click="saveCustomDivideZone"
    >
      <div class="dialog-warningSetting">
        <ul>
          <li v-for="(divideZoneItem, index) in divideZone.divideZoneArray" :key="divideZoneItem.id">
            <span class="warning-title">阶段{{ index+1 }}： 溢出箱价 </span>
            <el-input v-model.number="divideZoneItem.minPercent" :readonly="!authorityHandle(51)" class="price-input" />
            <i style="margin: 0 3px;"> — </i>
            <el-input v-model.number="divideZoneItem.maxPercent" :readonly="!authorityHandle(51)" class="price-input" />

            <i
              v-if="authorityHandle(51)"
              v-show="index != 0"
              class="el-icon-remove"
              @click="removeDivideZoneItem(index)"
            />
            <i
              v-if="authorityHandle(51)"
              v-show="index === divideZone.divideZoneArray.length-1"
              class="el-icon-circle-plus"
              @click="addDivideZoneItem"
            />
          </li>
        </ul>
      </div>
    </k-dialog>
    <!-- 分阶段设置 弹窗 -->
    <k-dialog
      :show-hide.sync="stageSetUpDialog"
      :modal-append-to-body="false"
      :append-to-body="true"
      title="分阶段设置"
      no-btn-text="确认修改"
      :close-fun="handleCloseSetUpDialog"
      :show-foot="false"
      :two-btn="authorityHandle(51)"
      @click="stageSetUpSave"
    >
      <el-radio-group
        v-model="probilityType"
        fill="#3b425d"
        text-color="#ffffff"
        class="top-radio-group"
        @change="probilityTypeChange"
      >
        <el-radio-button :label="1">用户通道</el-radio-button>
        <el-radio-button :label="2">主播通道</el-radio-button>
      </el-radio-group>
      <div class="dialog-warningSetting">
        <ul v-if="probilityType === 1">
          <div>
            <k-button class="top-btn" value="复制用户通道至主播通道" @click.native="cpoyMesData" />
          </div>
          <p style="color:#3b425d;margin-right:20px">系统提示: </p>
          <li v-for="(divideStateItem, index) in divideStage.divideStageArray" :key="divideStateItem.id">
            <span class="warning-title">{{ index + 1 }} 阶临界次数为 </span>
            <el-input v-model.number="divideStateItem.minNum" :readonly="!authorityHandle(51)" class="price-input" />
            <i style="margin: 0 3px;"> — </i>
            <el-input v-model.number="divideStateItem.maxNum" :readonly="!authorityHandle(51)" class="price-input" />次
          </li>
          <li>
            <span class="warning-title">一 轮 收 益 为 </span>
            {{ divideStage.profit }}
          </li>
          <li>
            <span class="warning-title">一 阶 临 界 次 数</span>
            {{ divideStage.phaseOne }}
          </li>
          <li>
            <span class="warning-title">二 阶 临 界 次 数</span>
            {{ divideStage.phaseTwo }}
          </li>
          <li>
            <span class="warning-title">一 轮 次 数 为 </span>
            {{ divideStage.size }}
          </li>
          <li>
            <span class="warning-title">单 次 收 益 为 </span>
            {{ divideStage.oneProfit }}
          </li>
          <li>
            <span class="warning-title">单 次 利 润 为 </span>
            {{ divideStage.percent }}
          </li>
        </ul>
        <ul v-if="probilityType === 2">
          <p style="color:#3b425d;margin-right:20px">系统提示: </p>
          <li v-for="(divideStateItem, index) in divideStage.divideStageArray" :key="divideStateItem.id">
            <span class="warning-title">{{ index + 1 }} 阶临界次数为 </span>
            <el-input v-model.number="divideStateItem.minNum" :readonly="!authorityHandle(51)" class="price-input" />
            <i style="margin: 0 3px;"> — </i>
            <el-input v-model.number="divideStateItem.maxNum" :readonly="!authorityHandle(51)" class="price-input" />次
          </li>
          <li>
            <span class="warning-title">一 轮 收 益 为 </span>
            {{ divideStage.profit }}
          </li>
          <li>
            <span class="warning-title">一 阶 临 界 次 数</span>
            {{ divideStage.phaseOne }}
          </li>
          <li>
            <span class="warning-title">二 阶 临 界 次 数</span>
            {{ divideStage.phaseTwo }}
          </li>
          <li>
            <span class="warning-title">一 轮 次 数 为 </span>
            {{ divideStage.size }}
          </li>
          <li>
            <span class="warning-title">单 次 收 益 为 </span>
            {{ divideStage.oneProfit }}
          </li>
          <li>
            <span class="warning-title">单 次 利 润 为 </span>
            {{ divideStage.percent }}
          </li>
        </ul>
      </div>
    </k-dialog>

    <!-- 二次确认弹框 -->
    <k-dialog
      custom-class="customClass"
      :show-hide.sync="openSetUpDialogBoxType"
      :modal-append-to-body="false"
      :append-to-body="true"
      title="概率确认"
      :show-foot="false"
      :two-btn="authorityHandle(43)"
      @click="handleSetUpDialogBox"
    >
      <div class="dialog-warningSetting">
        <el-table
          :data="GoodsShowProbability"
          fit
          border
          highlight-current-row
          style="width: 100%;border-radius:8px;"
          :header-cell-style="{background:'#F6F5FA',color:'#4E4F62'}"
          @sort-change="sortChange"
        >
          <el-table-column prop="goodsName" min-width="120px" label="饰品名称" show-overflow-tooltip align="center" />
          <el-table-column prop="customPrice" min-width="120px" sortable label="自定义价格" align="center" />
          <!--        <el-table-column prop="oldProbability" min-width="120px" label="原概率"  align="center">
          <editable-cell v-model="row.oldProbability" slot-scope="{row}" :show-input="row.editMode" @keyup.enter.native="changeProbability(row)"  >
            <span slot="content" >{{ row.oldProbability }}</span>
          </editable-cell>
        </el-table-column> -->
          <el-table-column prop="oldProbability" min-width="120px" label="原概率" align="center" />
          <!-- <el-table-column prop="newProbability" min-width="120px" label="新概率"  align="center">
          <editable-cell v-model="row.newProbability" slot-scope="{row}" :show-input="row.editMode" @keyup.enter.native="changeProbability(row)"  >
            <span slot="content" >{{ row.newProbability }}</span>
          </editable-cell>
        </el-table-column> -->
          <el-table-column prop="newProbability" min-width="120px" label="新概率" align="center" />
        </el-table>
      </div>
    </k-dialog>
  </div>
</template>

<script>
import { taskSetGoodsShowProbability, taskGetGoodsShowProbability, taskCopyBoxStageRoundList, updateGoodsPrice, setOpenProbabilityConfig, setBoxStageRoundList, getBoxStageRoundList, getBoxStageList, setBoxStageList, getOpenProbabilityConfig } from '@/api/task/index'
import { getCategoryList } from '@/api/babylib/platformlib/listdata'
import EditableCell from '@/components/EditableCell'
import { showLoading, hideLoading } from '@/utils/loading'
import * as math from 'mathjs'

export default {
  name: 'Openboxconfig',
  components: { EditableCell },
  data() {
    return {
      openSetUpDialogBoxType: false,
      goodsList: [],
      goodsValueModel: [],
      checkedGoodsList: [],
      boxId: -1,
      currentBoxName: '',
      probilityType: 1,
      divideZone: {
        divideZoneArray: [{
          id: undefined,
          boxId: undefined,
          minPercent: '',
          maxPercent: '',
          openSort: 0
        }]
      },
      divideStage: {
        profit: 0,
        size: 0,
        oneProfit: 0,
        percent: 0,
        phaseOne: 0,
        phaseTwo: 0,
        divideStageArray: [{
          id: undefined,
          boxId: undefined,
          probabilityId: -1,
          minNum: 0,
          maxNum: 0,
          openSort: 0
        }]
      },
      customDivideZoneDialog: false,
      stageSetUpDialog: false,
      categoryList: [],
      profitList: [], // 期望利润
      rowNewDataList: [], // 拼凑的列概率数据
      rebate: 100, // 箱子折扣 保存箱子配置时必传',
      price: 0, // 箱子价格 保存箱子配置时必传',
      coinModel: -1,
      tableDataList: [], // 表格数据
      tempTableData: [], // 表格数据
      tableConcatData: [], // 表格链接数据 整体一个数组
      listQuery: {
        id: undefined,
        categoryId: undefined, // 饰品分类,
        exteriorId: undefined, // 饰品外观',
        qualityId: undefined, // 饰品类别',
        rarityId: undefined, // 饰品品质',
        name: undefined // 饰品名称'
      },
      // 全部数据
      resultList: [],
      resultOpList: [], // 去重后的数据
      multipleSelection: [],
      addBaby: {
        showHide: false
      },
      currentOpIndex: 0,
      key: 1,
      // 添加动态列
      startIndex: 5, // 固定列起始index
      colNums: 2, // 固定概率列个数
      columnIndexArry: [],
      columnStartIndexArry: [],
      columnEndIndexArry: [],
      GoodsShowProbability: []
    }
  },
  computed: {
    hasNoData() {
      return !this.tableDataList.length
    },
    boxPriceComputed: function() {
      return (this.price / this.coinModel).toFixed(2)
    }
  },
  created() {
    this.boxId = this.$route.query.id
    this.price = this.$route.query.price
    this.rebate = this.$route.query.rebate
    this.coinModel = this.$route.query.coinModel
    // this.currentBoxName = sessionStorage.currentBoxName
    this.currentBoxName = ''
    this.loadData()
    this.getCategory()
    this.getBoxStageList(this.boxId)
  },
  methods: {
    copyProbablityA(index) {
      this.$log(index)
      this.$confirm('确定要复制用户通道去覆盖其他通道么, 是否继续?', '提示', {
        confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning'
      }).then(() => {
        this.getCopyProbality(index)
      }).catch(() => {
        this.$message({ type: 'info', message: '取消复制' })
      })
    },
    handleBabyTagDelete(index) {
      this.checkedGoodsList.splice(index, 1)
      this.goodsValueModel.splice(index, 1)
    },
    // 删除饰品
    deletebaby(index) {
      const _vue = this
      if (_vue.multipleSelection.length < 1) {
        this.$message.error('请至少选择一条数据进行删除！')
        return
      }
      const selections = _vue.multipleSelection
      this.$confirm('确定删除选中的饰品么?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        var ids = []
        for (var i = 0; i < selections.length; i++) {
          ids.push(selections[i].id)
        }
        this.tableDataList[index] = this.tableDataList[index].filter(item => !ids.includes(item.id))
        this.tableConcatData = this.tableConcatData.filter(item => !ids.includes(item.id))
        // this.key = this.key + 1
        this.$forceUpdate()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        })
      })
    },
    // 去重
    getDifferentArr(allArr, partArr) {
      for (let i = allArr.length - 1; i >= 0; i--) {
        for (let j = 0; j < partArr.length; j++) {
          if (allArr[i].itemId === partArr[j].itemId) {
            allArr.splice(i, 1)
            break
          }
        }
      }
      return allArr
    },
    // 添加饰品
    addBabyDialog(index) {
      this.resetbabyData()
      this.currentOpIndex = index
      this.addBaby.showHide = true
      const tempList = []
      Object.assign(tempList, this.resultList)
      this.resultOpList = this.getDifferentArr(tempList, this.tableConcatData)
      // this.$log('tableConcatData', this.tableConcatData)
      // this.$log('resultList', this.resultList)
    },
    // 保存 数据
    saveGoodsList() {
      if (this.checkedGoodsList.length < 1) {
        this.$message.error('请选择饰品添加！')
        return
      }
      this.tableDataList[this.currentOpIndex].push(...this.checkedGoodsList)
      this.tableConcatData.push(...this.checkedGoodsList)
      // this.key = this.key + 1
      this.addBaby.showHide = false
    },
    // 饰品选择事件
    selectChange(item) {
      const itemIndex = this.checkedGoodsList.findIndex((v) => {
        return v.lineId === item.lineId
      })
      if (itemIndex === -1) {
        this.checkedGoodsList.push(item)
      } else {
        this.checkedGoodsList.splice(itemIndex, 1)
      }
      this.$log(this.checkedGoodsList)
    },
    // 自定义阶段分区智能分区
    customDivideZone() {
      this.customDivideZoneDialog = true
    },
    getBoxStageList(boxId) {
      getBoxStageList({ boxId }).then(res => {
        this.divideZone.divideZoneArray = res.data
      })
    },
    saveCustomDivideZone() {
      setBoxStageList(this.divideZone.divideZoneArray).then(res => {
        if (res.data.success) {
          this.$message.success('保存成功')
          this.customDivideZoneDialog = false
          // this.loadData()
          this.loadTableData(res.data.data)
        } else {
          this.$message.error(res.data.msg)
        }
      })
    },
    // 分阶段设置？
    stageSetUp() {
      this.probilityType = 1
      this.stageSetUpDialog = true
      this.getBoxStageRoundList(1)
    },
    probilityTypeChange(val) {
      this.getBoxStageRoundList(val)
    },
    getBoxStageRoundList(probabilityId) {
      getBoxStageRoundList({ 'id': this.boxId, 'probabilityId': probabilityId }).then(res => {
        this.divideStage.divideStageArray = res.data.roundList
        this.divideStage.profit = res.data.profit
        this.divideStage.size = res.data.size
        this.divideStage.oneProfit = res.data.oneProfit
        this.divideStage.percent = res.data.percent
        this.divideStage.phaseOne = res.data.phaseOne
        this.divideStage.phaseTwo = res.data.phaseTwo
      })
    },
    stageSetUpSave() {
      setBoxStageRoundList(this.divideStage.divideStageArray).then(res => {
        if (res.data.success) {
          this.$message.success('保存成功')
          this.stageSetUpDialog = true
          let num
          if (this.probilityType == 1) {
            num = 1
          } else {
            num = 2
          }
          this.getBoxStageRoundList(num)
          this.loadData()
        } else {
          this.$message.error(res.data.msg)
        }
      })
    },
    removeDivideZoneItem(index) {
      // const index = this.divideZone.divideZoneArray.findIndex(function(item) {
      //   return item.id === value
      // })
      if (index !== -1) {
        this.divideZone.divideZoneArray.splice(index, 1)
      }
      this.divideZone.divideZoneArray.map((item, index) => {
        item.openSort = index
      })
    },
    addDivideZoneItem() {
      this.divideZone.divideZoneArray.push({
        id: undefined,
        boxId: this.boxId,
        minPercent: '',
        maxPercent: '',
        openSort: this.divideZone.divideZoneArray.length
      })
    },
    // 完成配置
    finishSetting() {
      if (this.tableDataList.length <= 0) {
        this.$message.warning('请添加饰品数据')
        return
      }
      const sumList = []
      for (let k = 0; k < this.tableDataList.length; k++) {
        for (let i = 0; i < this.colNums; i++) {
          sumList.push(Number(this.probilitySumCal(i, k)))
        }
      }
      const isFlag = sumList.every(item => item === 100)
      if (!isFlag) {
        this.$message.warning('请确保概率和 ∑ 等于100')
        return
      }
      this.$confirm('确定保存当前配置吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.rowNewDataList = []
        for (let i = 0; i < this.tableDataList.length; i++) {
          for (let k = 0; k < this.colNums; k++) {
            // 因为有一个后台隐藏的概率 F  所以G 概率的probabilityId为多加1  是7
            this.getProbalityColumnData(i, k)
          }
        }
        const settingData = {
          boxId: this.boxId,
          itemList: this.rowNewDataList
        }
        // if (settingData.itemList.length <= 0) return
        setOpenProbabilityConfig(settingData).then(res => {
          if (res.data.success) {
            this.rowNewDataList = []
            this.$message.success(res.data.msg)
          } else {
            this.rowNewDataList = []
            this.$message.error(res.data.msg)
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        })
      })
    },
    getProbalityColumnData(index, probabilityListIndex) {
      const stageData = this.tableDataList[index]

      if (probabilityListIndex == 0) {
        for (let j = 0; j < stageData.length; j++) {
          const itemId = stageData[j].itemId
          const probabilityList = stageData[j].userProbability
          this.rowNewDataList.push(
            { itemId: itemId, probability: probabilityList, openSort: index, probabilityId: 1 }
          )
        }
      }

      if (probabilityListIndex == 1) {
        for (let j = 0; j < stageData.length; j++) {
          const itemId = stageData[j].itemId
          const probabilityList = stageData[j].fissionProbability
          this.rowNewDataList.push(
            { itemId: itemId, probability: probabilityList, openSort: index, probabilityId: 2 }
          )
        }
      }
    },
    getCopyProbality(index) {
      const stageData = this.tableDataList[index]
      if (stageData.length === 0) {
        this.$message({ type: 'error', message: '无数据' })
        return
      }
      stageData.map(item => {
        const probilityDataA = item.userProbability
        item.fissionProbability = probilityDataA
      })
      // this.key = this.key + 1
      this.$message({ type: 'success', message: '复制成功' })
    },
    // 用户概率求和
    probilitySumCal(index, itemIndex) {
      let sum = 0
      this.tableDataList[itemIndex].map(item => {
        sum += Number(item.userProbability)
      })
      return sum.toFixed(2)
    },

    // 用户期望价格
    expectedPriceCal(index, itemIndex) {
      let sum = 0
      this.tableDataList[itemIndex].map(item => {
        sum += item.customPrice * item.userProbability / 100
      })
      const expectedPrice = sum.toFixed(2)
      return expectedPrice
    },

    // 主播期望价格
    fissionExpectedPriceCal(index, itemIndex) {
      let sum = 0
      this.tableDataList[itemIndex].map(item => {
        if (item.fissionProbability == null) { // 判断非0
          item.fissionProbability = 0
        }
        sum += item.customPrice * item.fissionProbability / 100
      })
      const expectedPrice = sum.toFixed(2)
      return expectedPrice
    },

    // 主播概率求和
    fissionProbilitySumCal(index, itemIndex) {
      let sum = 0
      this.tableDataList[itemIndex].map(item => {
        if (item.fissionProbability == null) { // 判断非0
          item.fissionProbability = 0
        }
        sum += Number(item.fissionProbability)
      })
      return sum.toFixed(2)
    },

    // 概率输入确认
    inputChange(event, index, itemIndex) {
      this.probilitySumCal(index, itemIndex)
    },
    // 初始化数据
    loadData() {
      this.resultList = JSON.parse(sessionStorage.goodsList)
      this.$log('初始化数据', this.resultList)
      this.refreshPage(this.boxId)
    },
    generateIndexArry() {
      for (let i = 0; i < this.colNums * 2; i++) {
        this.columnIndexArry.push(this.startIndex++)
      }
      this.startIndex = 5
      for (let i = 0; i < this.columnIndexArry.length; i++) {
        if (i % 2 === 0 && i !== this.columnIndexArry.length - 1) {
          this.columnStartIndexArry.push(this.columnIndexArry[i])
        } else {
          this.columnEndIndexArry.push(this.columnIndexArry[i])
        }
      }
    },
    initColumn() {
      this.colNums = 2
      this.columnIndexArry = []
      this.columnStartIndexArry = []
      this.columnEndIndexArry = []
      this.generateIndexArry()
    },
    arraySpanMethod({ row, column, rowIndex, columnIndex }) {
      for (var item of this.columnStartIndexArry) {
        if (columnIndex === item) {
          return [1, 2]
        } else if (columnIndex === item + 1) {
          return [0, 0]
        }
      }
    },

    // 选择项发生变化时会触发该事件
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    // 获取饰品分类
    getCategory() {
      getCategoryList().then(res => {
        const data = res.data
        this.categoryList = data
      })
    },
    // 搜索查询事件
    handleFilter() {
      showLoading()
      const tempFilter = {}
      for (const key in this.listQuery) {
        if (key !== 'id' && typeof (this.listQuery[key]) !== 'undefined' && this.listQuery[key] != null && this.listQuery[key] !== '') {
          tempFilter[key] = this.listQuery[key]
        }
      }
      this.$log('tempFilter', tempFilter)
      const searchResultList = []
      if (Object.keys(tempFilter).length === 0) {
        this.tableDataList = this.tempTableData
        // this.key = this.key + 1
        this.$forceUpdate()
        hideLoading()
        return
      }
      for (let i = 0; i < this.tempTableData.length; i++) {
        const tempList = this.tempTableData[i].filter(item => {
          let flag = false
          for (const key in tempFilter) {
            if (!item[key]) {
              flag = false
              break
            }
            if (item[key].toString().indexOf(tempFilter[key].toString()) >= 0) {
              flag = true
            } else {
              flag = false
              break
            }
          }
          if (flag) {
            return item
          }
        })
        // if (tempList.length > 0) {
        searchResultList.push(tempList)
        // }
      }
      this.tableDataList = []
      this.tableDataList.push(...searchResultList)
      this.$log(this.tableDataList)
      hideLoading()
      this.$forceUpdate()
      // this.key = this.key + 1
    },
    upcustomPrice(row) {
      const price = row.customPrice
      const itemId = row.itemId
      updateGoodsPrice({ id: itemId, prizePrice: price }).then(res => {
        if (!res.data.success) {
          this.$message.error(res.data.msg)
        }
      })
    },
    resetbabyData() {
      this.checkedGoodsList = []
      this.goodsValueModel = []
    },
    handleCloseDialog() {
      this.resetbabyData()
      this.addBaby.showHide = false
    },
    // 获取箱子的饰品概率
    refreshPage(id) {
      this.listQuery.id = id
      getOpenProbabilityConfig({ boxId: id }).then(res => {
        const data = res.data
        this.loadTableData(data)
      })
    },
    loadTableData(data) {
      if (data.length <= 0) {
        this.tableDataList = []
        return
      }
      this.tableDataList = []
      this.tableConcatData = []
      this.tempTableData = []
      for (let i = 0; i < data.length; i++) {
        const getHandList = data[i].map(row => {
          return {
            ...row,
            editMode: false,
            lineName: row.name,
            lineId: row.itemId
          }
        })
        this.tableConcatData = this.tableConcatData.concat(getHandList)
        this.tableDataList.push(getHandList)
      }
      Object.assign(this.tempTableData, this.tableDataList)
      this.initColumn()
    },

    // 确认分阶段设置
    handleCloseSetUpDialog(res) {
      if (typeof (res) == 'function') { // 判断是关闭按钮 还是 确认修改
        this.openSetUpDialogBoxType = false
      } else { // 打开概率确认弹框
        if (this.probilityType == 1) { // 只有用户通道会有弹框
          this.getBoxGetGoodsShowProbability()
          this.openSetUpDialogBoxType = true
        }
      }
      // }
    },

    // 分阶段设置 数据
    getBoxGetGoodsShowProbability() {
      const obj = {
        boxId: this.boxId
      }
      taskGetGoodsShowProbability(obj)
        .then(res => {
          this.GoodsShowProbability = res.data
          this.GoodsShowProbability.editMode = false
        })
    },

    // 使用原来概率
    openSetUpDialogBox() {
      // 创建数据模型
      const obj = {
        boxId: this.boxId,
        probabilityList: []
      }
      this.GoodsShowProbability.forEach(element => {
        const res = {
          goodsId: element.goodsId,
          probability: element.oldProbability
        }
        obj.probabilityList.push(res)
      })
      // 判断概率和是否等于100
      if (!this.compNumber(obj)) {
        return
      }

      // 请求接口
      this.getBoxSetGoodsShowProbability(obj)
    },

    // 使用新概率
    handleSetUpDialogBox(res) {
      if (typeof (res) == 'function') { // 判断是关闭按钮 还是 确认修改
        this.openSetUpDialogBoxType = false
      } else { // 打开概率确认弹框
        // 创建数据模型
        const obj = {
          boxId: this.boxId,
          probabilityList: []
        }
        this.GoodsShowProbability.forEach(element => {
          const res = {
            goodsId: element.goodsId,
            probability: element.newProbability
          }
          obj.probabilityList.push(res)
        })

        // 判断概率和是否等于100
        if (!this.compNumber(obj)) {
          return
        }

        // 请求接口
        this.getBoxSetGoodsShowProbability(obj)
      }
    },

    // 判断概率和是否等于100
    compNumber(obj) {
      const numarr = []
      obj.probabilityList.forEach((res) => { // 遍历拿到所有的数据 组成数组
        numarr.push(math.bignumber(res.probability * 1))
      })

      const addNumber = math.format( // 求总和
        math.add(...numarr)
      )

      const deff = math.format( // 求 100与其差值
        math.subtract(
          math.bignumber(100), math.bignumber(addNumber)
        )
      )
      console.log(addNumber)
      if (addNumber != 100) { // 输出文案
        this.$message.warning('概率和必须达到100,目前概率是' + addNumber + ',目前差' + deff)
        this.openSetUpDialogBoxType = true
        return false
      } else {
        return true
      }
    },

    // 保存概率数据
    getBoxSetGoodsShowProbability(obj) {
      taskSetGoodsShowProbability(obj)
        .then(res => {
          this.openSetUpDialogBoxType = false
          this.$message.success('ok')
        })
    },

    // 改变概率
    changeProbability(res) {
    },

    // 表格的排序条件发生变化的时候会触发该事件
    sortChange(column, prop, order) {
    },

    // 复制用户通道到主播
    cpoyMesData() {
      taskCopyBoxStageRoundList({ id: this.boxId }).then(res => {
        if (res.data.success) {
          this.$message.success('操作成功')
        } else {
          this.$message.error(res.data.msg)
        }
      })
    }
  }

}
</script>
<style lang="scss" scoped>
$menuText: #14162E; // 侧边栏字体颜色
$hoverColor: #1D143C; // 鼠标停留主色调浅色
$mainColor: #3b425d; // 主色调

.stage_flag {
  height: 22px;
  width: 80px;
  line-height: 22px;
  background: $mainColor;
  color: white;
  text-align: center;
  border-radius: 20px;
}

::v-deep .customClass {
  .el-dialog__body {
    .twoBtn {
      button {
        &:last-child {
          display: none !important;
        }
      }

    }
  }
}

::v-deep .el-radio-button__inner {
  &:hover {
    color: $mainColor;
  }
}

.dialog-warningSetting {
  margin: 30px;

  ::v-deep.el-input {
    width: 110px;
  }

  .price-input {
    width: 150px;
  }

  .el-icon {

    &-circle-plus,
    &-remove {
      font-size: 22px;
      color: #3b425d;
      margin-left: 10px;

    }
  }

  ul {
    list-style-type: none;
    margin: 0;
    padding: 0;

    li {
      margin: 0 0 30px 0px;
      display: flex;
      flex-direction: row;
      align-items: center;

      .warning-title {
        font-size: 16px;
        color: #14162E;
        margin-right: 30px;
      }

      i {
        color: #D1D5DD;
      }
    }
  }
}

.app-container {
  padding: 30px;
  height: 100%;
}

.filter-container {
  margin-bottom: 0px;
  width: 100%;
  height: 48px;
  line-height: 48px;

  .filter-item {
    display: inline-block;
    vertical-align: middle;
    margin-bottom: 10px;
  }

  .kInput {
    position: absolute;
    right: 20px;
  }

  .filter-title {
    height: 48px;
    line-height: 48px;
    font-size: 16px;
    font-weight: 500;
    margin-right: 22px;
    color: #14162E;
  }

  .babyquality {
    margin-right: 20px;
  }

  .babylook,
  .babycategory {
    margin-right: 20px;
  }
}

.top-btn {
  margin: 30px 0px 10px 0px;

  &:nth-of-type(2) {
    margin-left: 20px;
  }
}

.kSelect .el-select .el-input .el-input__inner {
  width: 124px;
}

::v-deep .el-select .el-input.is-focus .el-input__inner {
  border-color: $mainColor;
}

::v-deep .el-input__inner:focus {
  border-color: $mainColor;
}

.top-right-btn-container {
  margin-bottom: 20px;
  position: relative;

  .boxpricediv {
    display: flex;
    flex-direction: row;
    justify-content: center;
    align-items: center;
    position: absolute;
    right: 20px;
    top: 30px;
  }

  .top-right-btn {
    margin-left: 80px;
  }
}

.addBaby_dialog {
  display: flex;
  flex-direction: row;
  justify-content: center;

  ::v-deep .el-dialog__body {
    width: 678px;
    margin: 40px 80px;
  }

  ::v-deep .el-select .el-select__tags>span {
    display: none;
  }

  .el-tag+.el-tag {
    margin-left: 10px;
  }

  .el-tag {
    color: $mainColor;
    background-color: #ffffff;
    border-color: $mainColor;

    ::v-deep .el-tag__close {
      color: $mainColor;
    }

    ::v-deep .el-icon-close:hover {
      color: #ffffff;
      background: $mainColor;
    }
  }
}

::v-deep .el-icon {

  &-circle-plus,
  &-remove {
    font-size: 15px;
    color: $mainColor;
    margin-left: 10px;
  }
}

.headeradd {
  display: flex;
  flex-direction: row;
  justify-content: center;
  align-items: center;

  :nth-child(1) {
    margin-right: 10px;
  }
}

.price-div {
  display: flex;
  flex-direction: row;
  justify-content: center;
  align-items: center;

  ::v-deep .el-input__inner {
    padding: 0 5px
  }
}

.router-link {
  color: #409eff;

  &:hover {
    color: $mainColor;
  }

  &-no {}
}

.top-radio-group {
  margin-bottom: 20px;
}

.hasnodata_item {
  display: flex;
  flex-direction: row;
  justify-content: center;
  margin-top: 100px;
  font-size: 15px;
}
</style>
